#include "urlrecogniser.h"
#include "appglobal.h"
#include "diskmap.h"
#include <QRegExp>

YDUrlRecogniser::YDUrlRecogniser(QObject* parent) :
    QObject(parent) {
}

YDUrlRecogniser::~YDUrlRecogniser() {
}

YDUrlRecogniser::url_map_t YDUrlRecogniser::recogniseUrl(const QString& str) const {
    url_map_t ret;

    if (!str.isEmpty()) {
        std::map<QString, QRegExp*> regMap = g.diskMap->getWebUrlRegMap();

        for(auto p : regMap) {
            QRegExp* r = p.second;
            QStringList lst = this->matchAll(r, str);

            if (!lst.isEmpty()) {
                ret[p.first] = lst;
            }
        }
    }

    return std::move(ret);
}

QStringList YDUrlRecogniser::matchAll(QRegExp* reg, const QString& str) const {
    QStringList ret;
    int pos = 0;

    while (true) {
        pos = reg->indexIn(str, pos);
        if (pos < 0) {
            break;
        }

        QString s = reg->cap(0);
        if (!s.isEmpty() && !ret.contains(s, Qt::CaseInsensitive)) {
            if (s.indexOf("http://", 0, Qt::CaseInsensitive) != 0) {
                s = QString("http://") + s;
            }
            ret.append(s);
        }

        pos += reg->matchedLength();
    }

    return std::move(ret);
}
